﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Live;
using System.Threading;

namespace Rung.Soft.Jx3Tookit.Addon.FarmAlertAddon.Utility
{
    public class SignInButton:Button
    {
        private LiveAuthClient authClient;
        public LiveConnectSession Session { get; set; }

        private void Initialize()
        {
            if (this.authClient == null)
            {
                List<string> scopes = new List<string>();

                this.authClient = new LiveAuthClient();
                this.authClient.Theme = ThemeType.Default;

                this.authClient.InitializeCompleted += new EventHandler<LoginCompletedEventArgs>(this.OnInitializeCompleted);
                this.authClient.InitializeAsync(scopes);
            }
        }

        private void OnInitializeCompleted(object sender, LoginCompletedEventArgs e)
        {
            this.authClient.InitializeCompleted -= new EventHandler<LoginCompletedEventArgs>(OnInitializeCompleted);
            this.OnLogin(e);
        }

        private void OnLogin(LoginCompletedEventArgs args)
        {
            LiveConnectSessionChangedEventArgs args2;
            this.Session = args.Session;
            if (args.Error != null)
            {
                args2 = new LiveConnectSessionChangedEventArgs(args.Error);
            }
            else
            {
                args2 = new LiveConnectSessionChangedEventArgs(args.Status, args.Session);
            }
            this.RaiseSessionChangedEvent(args2);
            if (args.Status == LiveConnectSessionStatus.Connected)
            {
                //this.SetButtonState(ButtonState.LogOut);
            }
        }

        private void RaiseSessionChangedEvent(LiveConnectSessionChangedEventArgs args)
        {
            EventHandler<LiveConnectSessionChangedEventArgs> sessionChanged = this.SessionChanged;
            if (sessionChanged != null)
            {
                sessionChanged.Invoke(this, args);
            }
        }

        public event EventHandler<LiveConnectSessionChangedEventArgs> SessionChanged;
 

    }
}
